import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {SERVER_URL} from '../../app/config';
import {BLOCK_URL} from '../../app/config';

export interface Block {
  hash: string;
  timestamp: string;
  index: number;
  data: string;
  previousHash: string;
}

@Injectable({
  providedIn: 'root'
})
export class PeerService {

  constructor(public http: HttpClient,) {
  }

  getPeers() {
    return this.http.get<Block>(BLOCK_URL + 'peers').toPromise();
  }

  getLatestHash(peer) {
    let port: number;
    port = peer.port - 3000;
    console.log('https://' + peer.ipAddress + ':' + port + '/getLatestHash');
    if (peer.ipAddress === '119.23.107.118') {
      return this.http.get<Block>('https://www.wenchiren.top' + ':' + port + '/getLatestHash');
    }
    return this.http.get<Block>('https://' + peer.ipAddress + ':' + port + '/getLatestHash');
  }

  testPeer(ip, port) {
    if (ip === '119.23.107.118') {
      return this.http.get<Block>('https://www.wenchiren.top' + ':' + port + '/getLatestHash');
    }
    return this.http.get<Block>('https://' + ip + ':' + port + '/getLatestHash');
  }

  addPeer(ip, port) {
    let p2p: number;
    p2p = Number(port) + 3000;
    const data = {
      'peer': 'ws://' + ip + ':' + p2p.toString(),
    };
    return this.http.post(BLOCK_URL + 'addPeer', data, {responseType: 'text'});
  }
}
